package com.herench.bridge;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.herench.bs.support.HttpClientSupport;
import com.herench.bs.utils.DataFormatUtils;
import com.herench.bs.utils.DesUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

/**
 * Created by ThinkPad on 2017/6/4.
 */
public class MessageProvider {

    private static final String VALIDATE_ACCOUNT_DETAIL = "ValidateAccountDetail";
    private static final String VALIDATE_TOTAL_ACCOUNT = "ValidateTotalAccount";

    public String validateTotalAccount(String inMsg,String payUrl) {

        Document outMsg = MsgTemplate.getTotalOutMsgTpl();
        Element ccbTransactionCountEl = outMsg.getRootElement().element("ReturnData").element("Data").element("DataRow");
        String transactionCount = "";
        String transactionAmount = "";
        Element resultEl = outMsg.getRootElement().element("Result").element("Info");
        Element serverInfoEl = outMsg.getRootElement().element("ServerInfo").element("Info");
        Element clientInfoEl = outMsg.getRootElement().element("ClientInfo").element("Info");

        serverInfoEl.addAttribute("DEV_DATE", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        clientInfoEl.addAttribute("OPT_DATE", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        try {
            //解析入参
            Document inMsgDoc = DocumentHelper.parseText(inMsg);
            Element element = inMsgDoc.getRootElement().element("CommitData").element("Data").element("DataRow");
            String dateStr = element.attributeValue("Reconciliation_Date");
            Date date = null;
            if (!StringUtils.isNotEmpty(dateStr)) {
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                date = calendar.getTime();
            } else {
                date = DataFormatUtils.parserDay(dateStr);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            String tempDateStr = DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd");
            serverInfoEl.addAttribute("DEV_ACCT", tempDateStr);
            clientInfoEl.addAttribute("OPT_ACCT",DataFormatUtils.getTimeString(new Date()));

            Map<String,Object> params = new HashMap<>();
            params.put("sysCode","100101");
            params.put("billDate",tempDateStr);
            params.put("billType","1");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("funcode", "720002");
            jsonObject.put("token", "token");
            jsonObject.put("args", DesUtil.encrypt(JSON.toJSONString(params)));
            String str = HttpClientSupport.doPost(payUrl, jsonObject.toString(), "UTF-8");
            JSONObject resJson = JSON.parseObject(str);
            JSONArray array = resJson.getJSONObject("data").getJSONArray("bills");
            if (array==null || array.size()==0){
                throw new RuntimeException("账单不存在");
            }
            transactionCount = (Integer.valueOf(array.getJSONObject(0).getString("transCount"))+Integer.valueOf(array.getJSONObject(0).getString("refoundCount")))+"";
            transactionAmount =  array.getJSONObject(0).getString("amount");
            resultEl.addAttribute("EXECUTE_STATUS", "0").addAttribute("EXECUTE_MESSAGE", "对账数据解析成功");
        } catch (DocumentException e) {
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", "入參XML格式错误!");
            e.printStackTrace();
        } catch (Exception e) {
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", e.getMessage());
            e.printStackTrace();
        }
        ccbTransactionCountEl.addAttribute("CCBTransactionCOUNT", transactionCount);
        ccbTransactionCountEl.addAttribute("CCBTransactionAMT", transactionAmount);
        return outMsg.asXML();
    }

    public String validateAccountDetail(String inMsg,String payUrl) {
        Document outMsg = MsgTemplate.getDetailOutMsgTpl();
        Element returnDataEl = outMsg.getRootElement().element("ReturnData").element("Data");
        Element resultEl = outMsg.getRootElement().element("Result").element("Info");
        Element serverInfoEl = outMsg.getRootElement().element("ServerInfo").element("Info");
        Element clientInfoEl = outMsg.getRootElement().element("ClientInfo").element("Info");
        serverInfoEl.addAttribute("DEV_DATE", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        clientInfoEl.addAttribute("OPT_DATE", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        try {
            //解析入参
            Document inMsgDoc = DocumentHelper.parseText(inMsg);
            Element element = inMsgDoc.getRootElement().element("CommitData").element("Data").element("DataRow");
            String dateStr = element.attributeValue("Reconciliation_Date");
            Date date = null;
            if (!StringUtils.isNotEmpty(dateStr)) {
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                date = calendar.getTime();
            } else {
                date = DataFormatUtils.parserDay(dateStr);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            String tempDateStr = DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd");
            serverInfoEl.addAttribute("DEV_ACCT", tempDateStr);
            clientInfoEl.addAttribute("OPT_ACCT", tempDateStr);


            Map<String,Object> params = new HashMap<>();
            params.put("channelCode","100101");
            params.put("billDate",tempDateStr);
            params.put("billType","2");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("funcode", "720002");
            jsonObject.put("token", "token");
            jsonObject.put("args", DesUtil.encrypt(JSON.toJSONString(params)));
            String str = HttpClientSupport.doPost(payUrl, jsonObject.toString(), "UTF-8");
            JSONObject resJson = JSON.parseObject(str);
            JSONArray array = resJson.getJSONObject("data").getJSONArray("bills");
            if (array==null || array.size()==0){
                throw new RuntimeException("账单不存在");
            }
                 for (int i =0;i<array.size();i++) {
                        JSONObject temp = array.getJSONObject(i);
                        Element dataRowEl = returnDataEl.addElement("DataRow");
                        dataRowEl.addAttribute("Terminal_Number", temp.getString("terminalId"));
                        dataRowEl.addAttribute("Pos_NO", temp.getString("outTransNo"));
                        dataRowEl.addAttribute("TRAN_AMT", temp.getString("totalAmount"));
                        String transType= null;
                        if (temp.getString("tradeType").equals("交易")){
                            transType = "1";
                        }else if (temp.getString("tradeType").equals("退款")){
                            transType = "3";
                        }
                        dataRowEl.addAttribute("TRAN_TYPE",transType );
                        dataRowEl.addAttribute("TRAN_DATE",  temp.getString("startTime"));
                        dataRowEl.addAttribute("Card_ID", temp.getString("buyerId"));
                        dataRowEl.addAttribute("System_RNO", "100101");
                }
            resultEl.addAttribute("EXECUTE_STATUS", "0").addAttribute("EXECUTE_MESSAGE",  "对账文件解析成功");
        } catch (DocumentException e) {
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", "入參XML格式错误!");
            e.printStackTrace();
        } catch (Exception e) {
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", e.getMessage());
            e.printStackTrace();
        }

        return outMsg.asXML();
    }


    public String validate(String inMsg,String payUrl) {
        Document outMsg = MsgTemplate.getCommonOutMsgTpl();
        Element resultEl = outMsg.getRootElement().element("Result").element("Info");
        try {
            //解析入参
            Document inMsgDoc = DocumentHelper.parseText(inMsg);
            Element clientInfoEl = inMsgDoc.getRootElement().element("ClientInfo").element("Info");
            String methodStr = clientInfoEl.attributeValue("METHOD");
            if (StringUtils.isNotEmpty(methodStr)) {
                if (StringUtils.trim(methodStr).equalsIgnoreCase(VALIDATE_ACCOUNT_DETAIL)) {
                    return this.validateAccountDetail(inMsg,payUrl);
                } else if (StringUtils.trim(methodStr).equalsIgnoreCase(VALIDATE_TOTAL_ACCOUNT)) {
                    return this.validateTotalAccount(inMsg,payUrl);
                }else {
                    throw new RuntimeException("入参报文方法名不正确");
                }
            } else {
                throw new RuntimeException("入參报文中方法名为空");
            }
        } catch (DocumentException e) {
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", "入參XML格式错误!");
        } catch (NullPointerException e) {
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", "入参方法标签为空!");
        }catch (Exception e){
            resultEl.addAttribute("EXECUTE_STATUS", "-1").addAttribute("EXECUTE_MESSAGE", e.getMessage());
        }
        return outMsg.asXML();
    }

}
